package com.tianyouxiu.springai.controller;

import com.tianyouxiu.springai.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

  private final ChatClient chatClient;
  private final ChatHistoryRepository chatHistoryRepository;

  @RequestMapping(value = "/chat", produces = "text/html;charset=UTF-8")
  public Flux<String> chat(String prompt, String chatId) {

    // 保存会话
    chatHistoryRepository.save("chat", chatId);
    // 请求模型
    return chatClient
        .prompt()
        .user(prompt)
        .advisors(a -> a.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
        .stream()
        .content();
  }
}
